import time

from selenium.webdriver.support.wait import  WebDriverWait
from selenium.webdriver.support.ui import Select

class Base():
    # 初始化
    def __init__(self,driver):
        self.driver =driver

    #网址
    def open_url(self,url):
        self.driver.get(url)
    #封装时间的方法
    def error_png(self):
        error_png=time.strftime('%Y%m%d%H%M%S')
        return error_png
    #封装事件方法
    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            # 出现异常进行截图 (且每次的截图不被覆盖，带有时间戳)
            self.driver.save_screenshot('../Png/'+self.error_png()+'.png')
            print(e)
    #输入事件
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    #点击事件
    def click(self,loc):
        self.find_element(loc).click()

    #打开一个新窗口
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])
    #frame
    def frame(self,loc):
        self.driver.switch_to_frame(self.frame(loc))
    #滑动像素
    def scroll_x(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')
    #滑动到底部
    def scroll_bottom(self):
        self.driver.execute_script(f'window.scrollTo(0,document.body.scrollHeight')

    # 根据值来选择
    def select_value(self, loc, z):
        value = Select(self.find_element(loc))
        value.select_by_value(z)

    # 根据下标来选择
    def select_index(self, loc, z):
        index = Select(self.find_element(loc))
        index.select_by_index(z)

    # 根据文本来选择
    def select_text(self, loc, z):
        text = Select(self.find_element(loc))
        text.select_by_visible_text(z)


